// 网络请求封装
const baseUrl = 'http://175.178.156.176:8092/task' // 这里替换为实际的API地址

// 接口路径映射
const apiPaths = {
  // 用户认证
  login: '/login',
  register: '/register',
  getUserInfo: '/getUserInfo',
  updateUserInfo: '/updateUserInfo',
  
  // 项目管理
  getProjects: '/getProjects',
  getProjectDetail: '/getProjectDetail',
  createProject: '/createProject',
  updateProject: '/updateProject',
  deleteProject: '/deleteProject',
  
  // 项目成员管理
  getProjectMembers: '/getProjectMembers',
  addProjectMember: '/addProjectMember',
  updateProjectMemberRole: '/updateProjectMemberRole',
  removeProjectMember: '/removeProjectMember',
  
  // 任务管理
  getTasks: '/getTasks',
  getTaskDetail: '/getTaskDetail',
  createTask: '/createTask',
  updateTask: '/updateTask',
  deleteTask: '/deleteTask',
  
  // 任务附件管理
  uploadTaskAttachment: '/uploadTaskAttachment',
  deleteTaskAttachment: '/deleteTaskAttachment',
  
  // 任务日志管理
  addTaskLog: '/addTaskLog',
  
  // 工作流管理
  getWorkflowStatuses: '/getWorkflowStatuses',
  addWorkflowStatus: '/addWorkflowStatus',
  updateWorkflowStatus: '/updateWorkflowStatus',
  deleteWorkflowStatus: '/deleteWorkflowStatus',
  
  // 团队管理
  getTeams: '/getTeams',
  getTeamDetail: '/getTeamDetail',
  createTeam: '/createTeam',
  updateTeam: '/updateTeam',
  deleteTeam: '/deleteTeam',
  
  // 团队成员管理
  getTeamMembers: '/getTeamMembers',
  addTeamMember: '/addTeamMember',
  updateTeamMemberRole: '/updateTeamMemberRole',
  removeTeamMember: '/removeTeamMember',
  
  // 统计
  getStatistics: '/getStatistics',
  getProjectProgress: '/getProjectProgress'
}

// 请求封装
function request(options) {
  const {
    url,
    method = 'POST', // 所有请求都为POST
    data = {},
    header = {},
    success,
    fail,
    complete
  } = options

  // 显示加载提示
  wx.showLoading({
    title: '加载中...',
    mask: true
  })

  // 添加默认请求头
  const defaultHeader = {
    'Content-Type': 'application/json',
    ...header
  }

  // 获取用户token（除了登录和注册接口）
  const noAuthUrls = [apiPaths.login, apiPaths.register]
  const needAuth = !noAuthUrls.includes(url)
  
  if (needAuth) {
    const token = wx.getStorageSync('token')
    if (token) {
      defaultHeader['token'] = token
    } else {
      console.warn('Token not found for authenticated request:', url);
    }
  } else {
    console.log('No auth required for:', url);
  }

  // 调用全局请求拦截器
  const app = getApp()
  if (app && typeof app.onRequest === 'function') {
    app.onRequest(url, method, data)
  }

  // 调试信息
  console.log('Making request to:', url);
  console.log('Request headers:', defaultHeader);
  console.log('Request data:', data);
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method,
      data,
      header: defaultHeader,
      success: (res) => {
        wx.hideLoading()
        
        // 调试信息
        console.log('Response from:', url, res);
        
        // 调用全局响应拦截器
        if (app && typeof app.onResponse === 'function') {
          app.onResponse(res.data)
        }
        
        // 根据您的API规范处理响应
        if (res.statusCode === 200) {
          const result = res.data
          // code等于200的时候，是操作正常的
          if (result.code === 200) {
            resolve(result)
            success && success(result)
          } else {
            // code等于400的时候是操作异常的
            wx.showToast({
              title: result.message || '请求失败',
              icon: 'none'
            })
            reject(result)
            fail && fail(result)
          }
        } else {
          // HTTP状态码不是200
          wx.showToast({
            title: '请求失败',
            icon: 'none'
          })
          reject(res)
          fail && fail(res)
        }
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        reject(err)
        fail && fail(err)
      },
      complete: (res) => {
        complete && complete(res)
      }
    })
  })
}

// POST请求（所有请求都为POST）
function post(url, data = {}, options = {}) {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

// GET请求（转换为POST）
function get(url, data = {}, options = {}) {
  return post(url, data, options)
}

// PUT请求（转换为POST）
function put(url, data = {}, options = {}) {
  return post(url, data, options)
}

// DELETE请求（转换为POST）
function del(url, data = {}, options = {}) {
  return post(url, data, options)
}

module.exports = {
  request,
  get,
  post,
  put,
  del,
  apiPaths
}